import requests
import _thread as thread
from robot import config, logging
from robot.drivers.AIY import AIY
logger = logging.getLogger(__name__)

aiy = AIY()

def _getUrl(api):
    host = config.get('/quark_ui/api_host', 'http://localhost:4096')
    validate = config.get('/quark_ui/validate', '')
    return '{}/{}?validate={}'.format(host, api, validate)

def _request(api, payload={}):
    try:
        requests.post(_getUrl(api), data=payload, timeout=3)
    except:
        logger.error('request failed')
        print(__name__, 'request failed')

def wakeup():
    if config.get('/quark_ui/enable', False):
        thread.start_new_thread(_request, ('robot/wakeUp', ()))

def event(name, args):
    if config.get('/quark_ui/enable', False):
        thread.start_new_thread(_request, ('robot/event', {'name': name, 'args': args}))

def think(what):
    if config.get('/quark_ui/enable', False):
        thread.start_new_thread(_request, ('robot/event', {'name': 'think', 'args': what}))

def say(what):
    if config.get('/quark_ui/enable', False):
        thread.start_new_thread(_request, ('robot/message', {'robot_msg': what}))

def off():
    if config.get('/quark_ui/enable', False):
        thread.start_new_thread(_request, ('robot/sleep', ()))

